<script setup lang="ts">
import { ref, onMounted, onUpdated } from 'vue'
import DataTable from 'datatables.net-vue3'
import DataTablesCore from 'datatables.net-bs4'
import 'datatables.net-select'
import '../../plugin/datatables.net-responsive'
import { db } from '../../db/db'
import { getUsers, getStudent, getOrganize, setRealName, setPassword } from '../../util/SessionUtil'
import DatatableRender from '../../components/DatatableRender.vue'
import PaymentDetail from '../../components/PaymentDetail.vue'
import $ from 'jquery'

DataTable.use(DataTablesCore)

const options: any = {
    responsive: true,
    select: true,
    aaSorting: [[6, 'desc']],// 排序
    language: {
        "sProcessing": "处理中...",
        "sLengthMenu": "显示 _MENU_ 项结果",
        "sZeroRecords": "没有匹配结果",
        "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
        "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
        "sInfoPostFix": "",
        "sSearch": "搜索:",
        "sUrl": "",
        "sEmptyTable": "表中数据为空",
        "sLoadingRecords": "载入中...",
        "sInfoThousands": ",",
        "oPaginate": {
            "sFirst": "首页",
            "sPrevious": "<",
            "sNext": ">",
            "sLast": "末页"
        },
        "oAria": {
            "sSortAscending": ": 以升序排列此列",
            "sSortDescending": ": 以降序排列此列"
        },
        "select": {
            "rows": {
                _: '选择了 %d 行',
                1: '选择了 1 行'
            }
        }
    },
    autoWidth: true
}

const tableData: any = ref([])

const columns = [
    { data: 'donationId', title: '捐赠ID', responsivePriority: 12, className: 'none' },
    {
        data: 'donationSubdivisionTypeId', title: '捐赠类型', render: '#donationSubdivisionType', responsivePriority: 1
    },
    { data: 'money', title: '金额', responsivePriority: 3 },
    { data: 'goodsName', title: '物品名称', responsivePriority: 4 },
    { data: 'goodsNumber', title: '物品数量', responsivePriority: 5 },
    { data: 'donor', title: '捐赠人', responsivePriority: 7 },
    { data: 'donationDate', title: '捐赠时间', responsivePriority: 8 },
    { data: 'donorPhoneNumber', title: '联系方式', responsivePriority: 6 },
    { data: 'postalStatus', title: '邮寄状态', responsivePriority: 9, render: '#postalStatus' },
    { data: 'payStatus', title: '支付状态', responsivePriority: 10, render: '#payStatus' },
    { data: 'purpose', title: '用途', responsivePriority: 11 },
    { data: null, title: '操作', responsivePriority: 2, render: '#operate' },
]

let dt
const table = ref()

const users = getUsers()

const loadTableData = async () => {
    tableData.value = await db.donation.where('username').equals(users.username).toArray()
}

onMounted(async () => {
    loadTableData()
    const pi = await db.platformInformation.toArray()
    ptInfo.value = pi.length > 0 ? pi[0] : {}
})

onUpdated(() => {
    // 因异步加载数据，导致宽度变化，需要重画
    dt = table.value.dt
    dt.columns.adjust().draw()
    $('.carousel').carousel()

    $('.datatable').off('click', '.payment').on("click", '.payment', function (e: any) {
        toPayment(e.currentTarget.dataset.id, e.currentTarget.dataset.money)
    })


})

let tempPayId = ''
const toPayment = async (id: string, m: string) => {
    tempPayId = id
    money.value = m
    $('#paymentModal').modal('show')
}

const tipModal = ref({
    class: '',
    title: '',
    content: ''
})

const confirmModal = ref({
    class: '',
    title: '',
    content: '',
    callBack: '',
    data: {}
})

const confirmEx = (callBack: string, data: any) => {
    $('#confirmModal').modal('hide')
    loadTableData()
}

const money = ref('')
const ptInfo: any = ref({})

const updatePaymentStatus = () => {
    db.donation.where('donationId').equals(tempPayId).modify({ payStatus: 1 })
    loadTableData()
}

const paymentSuccessed = () => {
    updatePaymentStatus()
    tipModal.value.class = 'text-success'
    tipModal.value.title = '支付成功'
    tipModal.value.content = '您好，您已支付成功！'
    $('#tipModal').modal('show')
}

</script>
<template>
    <div class="col-md-9 col-lg-10">
        <div class="br-pagebody mg-t-5 pd-x-30">
            <div class="br-section-wrapper">
                <div class="row">
                    <div class="col-md-12">
                        <DataTable :options="options" :data="tableData" :columns="columns"
                            class="table responsive nowrap" ref="table">
                            <template #donationSubdivisionType="props">
                                <DatatableRender tableName="donationSubdivisionType"
                                    filter-key="donationSubdivisionTypeId" :filter-value="props.cellData"
                                    display-key="donationSubdivisionTypeName" />
                            </template>
                            <template #postalStatus="props">
                                <span v-if="props.cellData == 0">未邮寄</span>
                                <span v-if="props.cellData == 1">已到</span>
                                <span v-if="props.cellData == 2">待审核</span>
                            </template>
                            <template #payStatus="props">
                                <span v-if="props.cellData == 0">未支付</span>
                                <span v-if="props.cellData == 1">已支付</span>
                                <span v-if="props.cellData == 2">待对账</span>
                            </template>
                            <template #operate="props">
                                <div class="btn-group" role="group" aria-label="Basic example"
                                    v-if="props.rowData.payStatus == 0 && props.rowData.donationSubdivisionTypeId == 1">
                                    <button type="button" class="btn btn-info btn-sm payment"
                                        :data-id="props.rowData.donationId"
                                        :data-money="props.rowData.money">支付</button>
                                </div>
                            </template>
                        </DataTable>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="tipModal" tabindex="-1" aria-labelledby="tipModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" :class="tipModal.class" id="tipModalLabel">{{ tipModal.title }}</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    {{ tipModal.content }}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!--确认Modal-->
    <div class="modal fade" id="confirmModal" tabindex="-1" aria-labelledby="confirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" :class="confirmModal.class" id="confirmModalLabel">{{ confirmModal.title }}
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    {{ confirmModal.content }}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary"
                        @click="confirmEx(confirmModal.callBack, confirmModal.data)">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!--支付框-->
    <PaymentDetail :money="money" :platformInformationData="ptInfo" @payment-successed="paymentSuccessed" />
</template>
<style>
@import 'datatables.net-bs4';
</style>